import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
Vue.use(VueRouter)

const Tabbar = () => import('@/components/app-tabbar.vue')
const Home = () => import('@/views/home')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const User = () => import('@/views/user')
const Article = () => import('@/views/article')
const UserProfile = () => import('@/views/user/components/profile')
const routes = [
  {
    path: '/',
    name: '/',
    components: {
      default: Home,
      tabbar: Tabbar
    }
  },
  {
    path: '/question',
    components: {
      default: Question,
      tabbar: Tabbar
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      tabbar: Tabbar
    }
  },
  { path: '/user', components: { default: User, tabbar: Tabbar } },
  { path: '/article', component: Article },
  { path: '/user/profile', component: UserProfile },
  {
    path: '/login',
    component: () => import('@/views/login')
    // beforeEnter: (to, from, next) => {
    //   next(false) // 阻止路由记录的添加
    // }
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const token = store.getters.token
  // 没登录并且访问/user下的路由
  if (!token && to.path.startsWith('/user')) {
    return next('/login?returnUrl=' + encodeURIComponent(to.fullPath))
  }
  if (from.path === '/login' && from.query.returnUrl) {
    const returnUrl = from.query.returnUrl
    delete from.query.returnUrl
    return next(returnUrl)
  }
  // 其他情况放行
  next()
})

export default router
